/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.machineryrental.weblayer.validator;

import cz.muni.fi.pa165.machineryrental.weblayer.custommodels.User;
import cz.muni.fi.pa165.machineryrental.weblayer.utils.DBUtil;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 *
 * @author jostri
 */
@Component
public class UserValidator implements Validator {

	@Autowired
	private DBUtil dbUtil;
	
	@Override
	public boolean supports(Class<?> type) {
		return User.class.equals(type);
	}

	@Override
	public void validate(Object o, Errors errors) {
		User u = (User)o;
		
		ValidationUtils.rejectIfEmpty(errors, "username", "login.username.empty");
		ValidationUtils.rejectIfEmpty(errors, "password", "login.password.empty");
		ValidationUtils.rejectIfEmpty(errors, "passwordConfirm", "login.passwordconfirm.empty");
		
		if (u.getPassword() != null && !u.getPassword().isEmpty() &&
				u.getPasswordConfirm() != null && !u.getPasswordConfirm().isEmpty()) {
			if (!u.getPassword().equals(u.getPasswordConfirm())) {
				errors.rejectValue("password", "login.password.notsame");
				errors.rejectValue("passwordConfirm", "login.password.notsame");
			}
		}
		
		if (u.getId() == 0) {
			if (u.getUsername() != null && !u.getUsername().isEmpty()) {
				try {
					if (this.dbUtil.existsUsername(u.getUsername())) {
						errors.rejectValue("username", "login.username.duplicit");
					}
				} catch (SQLException ex) {
					throw new DataAccessException(ex.getMessage()) {
					};
				}
			}
		}
	}
	
}
